package com.zlyx.easy.security.authentication.config;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.zlyx.easy.security.authentication.configurer.AbstractSecurityConfigurer;
import com.zlyx.easy.security.authentication.filter.RequestAuthorizationTokenFilter;

/**
 * <p>
 * 配置允许直接访问的接口
 * </p>
 *
 * @author 赵光
 * @version v1.0
 */
@Order(2)
@EnableWebSecurity
public class WebSecurityAdaptConfig extends WebSecurityConfigurerAdapter {

	private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfigurerAdapter.class);

	@Autowired
	private List<AbstractSecurityConfigurer> adapters;

	@Autowired
	private RequestAuthorizationTokenFilter authenticationTokenFilter;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and()
				.formLogin().and().logout().and().authorizeRequests().antMatchers("/login/**").permitAll()
				.antMatchers("/actuator/**").permitAll().antMatchers("/manage/**").permitAll().antMatchers("/oauth/**")
				.permitAll().anyRequest().authenticated();
		if (adapters != null) {
			adapters.forEach(adapter -> {
				try {
					http.apply(adapter);
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
				}
			});
		}
		http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
	}

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

}
